import {
    addReplyApi,
    delReplyApi,
    editReplyApi
} from '@/api/custcare/reply/reply'
import {
    AddReplyModel,
    ReplyModel,
    ReplyParam
} from '@/api/custcare/reply/ReplyModel'
import useInstance from '@/hooks/useInstance'
import { Result, StatusCode } from '@/http/request'
import { EditType } from '@/types/BaseEnum'
import { reactive, ref } from 'vue'

export default function useReply(getReplyTable: any) {
    const { global } = useInstance()

    const addEditRef = ref<{
        show: (type: string, row?: ReplyModel) => void
    }>()

    const addModel = reactive<ReplyModel>({
        id: '',
        editType: '',
        status: '1',
        key_words: '',
        question: '',
        content: '',
        img: '',
        group_id: 1,
        sort: 1
    })

    // 新增
    const addBtn = () => {
        addEditRef.value?.show(EditType.ADD, addModel)
    }

    // 编辑
    const editBtn = async (row: ReplyModel) => {
        row.status = String(row.status)
        addEditRef.value?.show(EditType.EDIT, row)
    }

    // 删除
    const delBtn = async (id: number) => {
        const confirm = await global.$eleConfirm('确定删除该数据吗？')
        if (confirm) {
            // 执行删除操作
            let res = await delReplyApi(
                reactive<ReplyParam>({
                    id: id
                })
            )
            if (res && res.code == StatusCode.Success) {
                // 刷新列表
                getReplyTable()
                // 信息提示
                global.$message({ message: res.msg, type: 'success' })
            }
        }
    }

    // 保存
    const save = async (param: ReplyModel) => {
        const menuParam = reactive<AddReplyModel>({
            id: param.id,
            editType: param.editType,
            status: parseInt(param.status),
            key_words: param.key_words,
            question: param.question,
            content: param.content,
            img: param.img,
            group_id: param.group_id,
            sort: param.sort
        })
        console.log('保存', menuParam)
        let res: Result
        if (param.editType == EditType.ADD) {
            res = await addReplyApi(menuParam)
        } else {
            res = await editReplyApi(menuParam)
        }
        if (res && res.code == StatusCode.Success) {
            // 刷新列表
            getReplyTable()
            // 信息提示
            global.$message({ message: res.msg, type: 'success' })
        }
    }

    return {
        addBtn,
        editBtn,
        delBtn,
        save,
        addEditRef
    }
}
